package guyubao.com.entity;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import lombok.Data;

import java.io.Serializable;

@Data
public class RestBean<T>implements Serializable {
    private static final long serialVersionUID = 3550021498355364894L;
    private int code;
    private T data;
    private String msg;
    
    public RestBean() {}
    
    public RestBean(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    public RestBean(int code, T data, String msg) {
        this.code = code;
        this.data = data;
        this.msg = msg;
    }
    
    public static <T> RestBean<T> success(T data){
        return new RestBean<>(200, data, "请求成功");
    }
    public static <T> RestBean<T> success(){return success(null);}
    public static <T> RestBean<T> failure(int code, String message){
        return new RestBean<>(code, null, message);
    }
    public static <T> RestBean<T> failure(int code){
        return failure(code, "请求失败");
    }
    public static <T> RestBean<T> failure(String message){
        return failure(400, message);
    }
    // 身份验证失败
    public static <T> RestBean<T> unauthorized(String message){return failure(401, message);}
    // 没有对应权限
    public static <T> RestBean<T> forbidden(String message){return failure(403, message);}


    //将当前对象转换为JSON格式的字符串用于返回
    public String asJsonString() {
        return JSONObject.toJSONString(this, JSONWriter.Feature.WriteNulls);
    }
}